package com.tourism.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tourism.common.Result;
import com.tourism.entity.ScenicSpot;
import com.tourism.mapper.ScenicSpotMapper;
import com.tourism.service.ScenicSpotService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class ScenicSpotServiceImpl extends ServiceImpl<ScenicSpotMapper, ScenicSpot> implements ScenicSpotService {

    @Override
    public Result getSpotById(Integer id) {
        if (id == null) {
            return Result.fail("ID不能为空");
        }
        ScenicSpot spot = getById(id);
        return Result.success(spot);
    }

    @Override
    public Result getSpotList(Integer page, Integer pageSize, String name, String location) {
        Page<ScenicSpot> pageParam = new Page<>(page, pageSize);
        LambdaQueryWrapper<ScenicSpot> wrapper = new LambdaQueryWrapper<>();

        if (name != null && !name.isEmpty()) {
            wrapper.like(ScenicSpot::getName, name);
        }
        if (location != null && !location.isEmpty()) {
            wrapper.like(ScenicSpot::getLocation, location);
        }

        wrapper.orderByDesc(ScenicSpot::getCreateTime);

        Page<ScenicSpot> pageResult = page(pageParam, wrapper);
        return Result.success(pageResult);
    }

    @Override
    public Result addSpot(ScenicSpot scenicSpot) {
        if (scenicSpot.getName() == null || scenicSpot.getName().isEmpty()) {
            return Result.fail("景点名称不能为空");
        }

        scenicSpot.setCreateTime(new Date());
        boolean success = save(scenicSpot);
        return success ? Result.success("") : Result.fail("添加失败");
    }

    @Override
    public Result updateSpot(ScenicSpot scenicSpot) {
        if (scenicSpot.getId() == null) {
            return Result.fail("ID不能为空");
        }

        boolean success = updateById(scenicSpot);
        return success ? Result.success("") : Result.fail("更新失败");
    }

    @Override
    public Result deleteSpot(Integer id) {
        if (id == null) {
            return Result.fail("ID不能为空");
        }

        boolean success = removeById(id);
        return success ? Result.success("") : Result.fail("删除失败");
    }

    @Override
    @Transactional
    public Result batchDeleteSpots(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.fail("ID列表不能为空");
        }

        boolean success = removeBatchByIds(ids);
        return success ? Result.success("") : Result.fail("批量删除失败");
    }

    @Override
    public Result getAllSpots() {
        List<ScenicSpot> spots = list();
        return Result.success(spots);
    }
}